<?php
namespace app\index\home;
use app\index\home\Base;
use app\index\model\Product as ProductModel;
use think\Db;
use app\index\home\Wxoauth;
use app\index\controller\Wxpay;
use think\Request;
class Product extends Base
{
    protected function initialize()
    {
       parent::initialize();
       
    }

    // 首页
    function index(){
        // echo "???";
        $where = [];
        // $pModel = new ProductModel();
        // $rs = $pModel->where($where)->select();
        $banner = Db::name('index_banner')->order('orders asc')->select();
        $zhekou_product = Db::name('product')->where(array('is_zhekou'=>1,'status'=>1))->order('orders asc')->select();
        $recommedn_product = Db::name('product')->where(array('is_recommend'=>1,'status'=>1))->order('orders asc')->select();
        $data['banner'] = $banner?$banner:'';
        $data['zhekou_product'] = $zhekou_product?$zhekou_product:'';
        $data['recommedn_product'] = $recommedn_product?$recommedn_product:'';
        okMsg($data);
    }

    // 获取banner
    function getBanner(){
        $type = input("type/d");//banner类型，1：产品展示，2：黄金单品，3：首页积分商场
        $list = Db::name('banner')->where(array('type'=>$type,'status'=>1))->order('orders asc')->select();
        if(!$list){
            $list = array();
        }
        okMsg($list);
    }
    // 一级分类列表
    function getFirstType(){
        $list = Db::name('product_type')->where(array('pid'=>1,'status'=>1))->order('orders asc')->field('id,name,banner')->select();
        if($list){
            foreach($list as $key=>&$value){
                $two_type_list = Db::name('product_type')->where(array('pid'=>$value['id'],'status'=>1))->order('orders asc')->field('id,pid,name,banner')->select();
                if($two_type_list){
                    $value['child'] = $two_type_list;
                }
                else{
                    $value['child'] = array();
                }
            }
        }
        okMsg($list);
    }

    // 根据一级分类获取二级分类及产品列表
    function getProductByType(){
        $pid = input('id/d');//二级分类id
        $page = input('start/d');
		$num = input('limit/d');
        $keyword = input('keyword/s');
        $order_by = input('order_by/s');

        if($order_by){
            if($order_by=='sell_num'){
                $orders = "buy_count desc";
            }
            elseif($order_by=="price"){
                $orders = "price asc";
            }
            elseif($order_by=="price_d"){
                $orders = "price desc";
            }
            elseif($order_by=='time'){
                $orders = 'ctime desc';
            }
        }
        else{
            $orders = 'ctime desc';
        }
        if(!$page){
            $page = 1;
        }
        if(!$num){
            $num = 10;
        }
        $star = ($page-1)*$num;

        $where[] = ['type_id','eq',$pid];
        $where[] = ['status','eq',1];

        if($keyword){
            $where[] = ['name','like','%'.$keyword.'%'];
            // $swhere[] = ['sub_name','like','%'.$keyword.'%'];
        }
        else{
            $swhere = [];
        }
        // $child_list = 
        $list = array();
        
        $list = Db::name('product')->where($where)->order($orders)->limit($star,$num)->select();
        // $sql = Db::name('product')->getLastSql();
        // echo $sql;exit;
        if(!$list){
            $data['start'] = -1;
            $list = array();
        }
        else{
            $data['start'] = $page+1;
        }

        $data['data'] = $list;
        $data['limit'] = $num;
        $data['text'] = '获取成功';
		$data['error'] = 200;
		echo json_encode($data);exit;
    }

    // 首页搜索产品列表
    function serchProduct(){
        $page = input('start/d');
		$num = input('limit/d');
        $keyword = input('keyword/s');
        
        $orders = 'ctime desc';

        if(!$page){
            $page = 1;
        }
        if(!$num){
            $num = 10;
        }
        $star = ($page-1)*$num;

        $where[] = ['status','eq',1];

        if($keyword){
            $where[] = ['name','like','%'.$keyword.'%'];
            // $swhere[] = ['sub_name','like','%'.$keyword.'%'];
        }
        else{
            $data['start'] = -1;
            $list = array();
            $data['data'] = $list;
            $data['limit'] = $num;
            $data['text'] = '获取成功';
            $data['error'] = 200;
            echo json_encode($data);exit;
        }
        // $child_list = 
        $list = array();
        
        $list = Db::name('product')->where($where)->order($orders)->limit($star,$num)->select();
        // $sql = Db::name('product')->getLastSql();
        // echo $sql;exit;
        if(!$list){
            $data['start'] = -1;
            $list = array();
        }
        else{
            $data['start'] = $page+1;
        }

        $data['data'] = $list;
        $data['limit'] = $num;
        $data['text'] = '获取成功';
		$data['error'] = 200;
		echo json_encode($data);exit;
    }
    // 产品详情
    function productDetail(){
        $openid = input('openid/s');
        // var_dump($openid);exit;
        $uid = $this->getUserId($openid);
        $product_id = input('product_id/d');
        $list = array();
        $product_info = Db::name('product')->where('id',$product_id)->field('id,name,sub_name,banner,show_price,show_price_inner,show_price_gift,line_price,shipping_price,describes,price,price_inner,price_gift,buy_count,other_buy_count,view_count,other_view_count,rest_num,share_img,spec,slcg_spec,slcg_price,slcg_rest_num,unit_transform,price_describe')->find();
        // echo Db::name('product')->getLastSql();exit;
        if(!$product_info){
            errMsg('无此产品');
        }
        if($product_info['describes']){
            $product_info['describes'] = html_entity_decode($product_info['describes']);
        }
        $product_info['buy_count'] = $product_info['buy_count']+$product_info['other_buy_count'];
        $list['product_info'] = $product_info;
        $pinglun_list = Db::name('product_consume')->alias('a')->join("user u",'a.uid=u.id','LEFT')->where(array('a.pid'=>$product_id,'a.status'=>0))->field('a.*,u.nickname,u.headimg')->select();
        $list['pinglun'] = $pinglun_list;
        $list['uid']=$uid;
        // $list['buy_count'] = $list['buy_count']+$list['other_buy_count'];
        // 浏览量+1
        Db::name('product')->where('id',$product_id)->setInc('view_count');
        okMsg($list);

    }

    // 产品详情
    function productDetailQuan(){
        // $openid = input('openid/s');
        //var_dump($openid);exit;
        // $uid = $this->getUserId($openid);
        $product_id = input('product_id/d');
        $list = array();
        $product_info = Db::name('product')->where('id',$product_id)->field('id,name,sub_name,banner,show_price,show_price_inner,show_price_gift,line_price,shipping_price,describes,price,price_inner,price_gift,buy_count,other_buy_count,view_count,other_view_count,rest_num,share_img,spec,slcg_spec,slcg_price,slcg_rest_num,unit_transform,price_describe')->find();
        // echo Db::name('product')->getLastSql();exit;
        if(!$product_info){
            errMsg('无此产品');
        }
        if($product_info['describes']){
            $product_info['describes'] = html_entity_decode($product_info['describes']);
        }
        $product_info['buy_count'] = $product_info['buy_count']+$product_info['other_buy_count'];
        $list['product_info'] = $product_info;
        $pinglun_list = Db::name('product_consume')->alias('a')->join("user u",'a.uid=u.id','LEFT')->where(array('a.pid'=>$product_id,'a.status'=>0))->field('a.*,u.nickname,u.headimg')->select();
        $list['pinglun'] = $pinglun_list;
        // $list['uid']=$uid;
        // $list['buy_count'] = $list['buy_count']+$list['other_buy_count'];
        // 浏览量+1
        Db::name('product')->where('id',$product_id)->setInc('view_count');
        okMsg($list);

    }

    // 加入购物车
    function addToShoppingCart(){
        $openid = input('openid/s');
        $uid = $this->getUserId($openid);
        $pro_id = input('product_id/d');
        $spec_select = input('spec/s');
        $spec_price = input('spec_price');
        $price_type = input('price_type/d');//选择价格类型，0：普通用户价格，1：内购价格，2：送礼采购价
        $num = input('num/d');
        $parent_id = input('parent_id/d');
        if(!$parent_id){
            $parent_id = 0;
        }

        $pro_info = Db::name('product')->where('id',$pro_id)->find();
        if(!$pro_info){
            errMsg('参数错误');
        }

        // 有选规格
        if($spec_select){
            // 获取数据库产品价格
            $pro_spec_arr = explode(',',$pro_info['spec']);
            if($price_type==0){
                $pro_price_arr = explode(',',$pro_info['price']);
                foreach($pro_spec_arr as $k=>&$v){
                    if($spec_select==$v){
                        $pro_info['pro_price'] = floatval($pro_price_arr[$k]);
                    }
                }
            }
            elseif($price_type==1){
                $pro_price_arr = explode(',',$pro_info['price_inner']);
                foreach($pro_spec_arr as $k=>&$v){
                    if($spec_select==$v){
                        $pro_info['pro_price'] = floatval($pro_price_arr[$k]);
                    }
                }
            }
            else{
                // 采购送礼价
                $pro_info['pro_price'] =  $pro_info['slcg_price'];
            }
            
            
        }
        // 没选规格
        else{
            if($price_type==0){
                $pro_info['pro_price'] = $pro_info['show_price'];
            }
            elseif($price_type==1){
                $pro_info['pro_price'] = $pro_info['show_price_inner'];
            }
            else{
                $pro_info['pro_price'] = $pro_info['slcg_price'];
            }
        }

        if($spec_price!=$pro_info['pro_price']){
            errMsg('前后端产品价格差异');
        }
		
        if($price_type==2){
            if($pro_info['rest_num']<intval($pro_info['unit_transform'])*$num){
                errMsg('该产品库存不足!');
            }
            
        }
        else{
            $spec_arr = explode(',',$pro_info['spec']);
            $rest_num_arr = explode(',',$pro_info['rest_num']);
            $spec_num = explode(',',$pro_info['spec_num']);
            foreach($spec_arr as $k=>&$v){
                if($spec_select==$v){
                    $rest_num_del = $spec_num[$k]*$num;
                    if($pro_info['rest_num']<$rest_num_del){
                        errMsg('该产品库存不足!!');
                    }
                }
            }
        }

        $price_sum = $spec_price*$num;
        $where = array(
            'uid'=>$uid,
            'pro_id'=>$pro_id,
            'spec_select'=>$spec_select,
            'spec_price'=>$spec_price,
            'price_type'=>$price_type
        );
        // 购物车存在相同的物品，数量累积，价格累积
        $record = Db::name('shopping_cart')->where($where)->value('id');
        if($record){
            $rs = Db::name('shopping_cart')->where('id',$record)->setInc('num',$num);
            $rs1 = Db::name('shopping_cart')->where('id',$record)->setInc('price_sum',$price_sum);
            okMsg();
        }
        else{
            if($parent_id>0&&$parent_id!=$uid){
                // 更新分享人信息
                Db::name('shopping_cart')->where('uid',$uid)->update(array('parent_id'=>$parent_id));
            }
            $in_data = array(
                'uid'=>$uid,
                'pro_id'=>$pro_id,
                'spec_select'=>$spec_select,
                'spec_price'=>$spec_price,
                'num'=>$num,
                'price_sum'=>$price_sum,
                'ctime'=>time(),
                'parent_id'=>$parent_id,
                'price_type'=>$price_type
            );
            $rs = Db::name('shopping_cart')->insert($in_data);
            if($rs){
                okMsg();
            }
            else{
                errMsg('路上太拥挤，请稍后再试');
            }
        }
        

    }

    // 购物车列表
    function shoppingCartProList(){
        $openid = input('openid/s');
        $uid = $this->getUserId($openid);

        $list = Db::name('shopping_cart')->where('uid',$uid)->alias('s')->join('product p','s.pro_id=p.id','LEFT')->field('s.*,p.name,p.sub_name,p.share_img')->select();
        if(!$list){
            $list = array();
        }

        $data['data'] = $list;
        $data['sum_price'] = $list = Db::name('shopping_cart')->where('uid',$uid)->sum('price_sum');
        okMsg($data);
    }

    // 购物车点击产品加减产品数量得出最终产品价格
    function jiesuanBtnEvent(){
        $openid = input('openid/s');
        $shopping_cart_id = input('shopping_cart_id');
        $num = input('num/d');
        $uid = $this->getUserId($openid);

        if($shopping_cart_id&&$num>0){
            $shipping_cart_info = Db::name('shopping_cart')->where('id',$shopping_cart_id)->field('spec_price,pro_id,spec_select,price_type')->find();
            // 采购送礼
            if($shipping_cart_info['price_type']==2){
                $rest_num = Db::name('product')->where('id',$shipping_cart_info['pro_id'])->field('rest_num,unit_transform')->find();
                if($rest_num['rest_num']<$num*$rest_num['unit_transform']){
                    errMsg('该产品库存不足');
                }
            }
            else{
                $product_info = Db::name('product')->where('id',$shipping_cart_info['pro_id'])->field('spec,rest_num,spec_num')->find();
                $spec_arr = explode(',',$product_info['spec']);
                // $rest_num_arr = explode(',',$product_info['rest_num']);
                $spec_num = explode(',',$product_info['spec_num']);
                foreach($spec_arr as $k=>&$v){
                    if($shipping_cart_info['spec_select']==$v){
                        $rest_num_del = $spec_num[$k]*$num;
                        if($product_info['rest_num']<$rest_num_del){
                            errMsg('该产品库存不足');
                        }
                    }
                }
            }
            // $spec_price = Db::name('shopping_cart')->where('id',$shopping_cart_id)->value('spec_price');
            $spec_price = $shipping_cart_info['spec_price'];
            $price_sum = $spec_price*$num;
            $rs = Db::name('shopping_cart')->where('id',$shopping_cart_id)->update(array('num'=>$num,'price_sum'=>$price_sum));
            // $data['sum_price'] = $list = Db::name('shopping_cart')->where('uid',$uid)->sum('price_sum');
            $data['sum_price'] = $price_sum;
            okMsg($data);
        }
        else{
            errMsg('参数错误');
        }
    }

    // 删除购物车产品
    function deleteShoppingCartPro(){
        $openid = input('openid/s');
        $shopping_cart_id = input('shopping_cart_id/s');
        $uid = $this->getUserId($openid);
        if(!$shopping_cart_id||!$uid){
            errMsg('参数错误');
        }
        $where[] = ['id','in',$shopping_cart_id];
        $where[] = ['uid','eq',$uid];
        $rs = Db::name('shopping_cart')->where($where)->delete();
        if($rs){
            $data['sum_price'] = $list = Db::name('shopping_cart')->where('uid',$uid)->sum('price_sum');
            okMsg($data);
        }
        else{
            errMsg('删除失败，请重试');
        }
    }

    // 结算(购物车结算或者是点击立即购买)
    function jiesuan(){
        $openid = input('openid/s');
        $type = input('type/d');//结算类型：1：结算购物车，2：立即购买某款产品
        $uid = $this->getUserId($openid);

        $price_sum = 0;

        $is_cgsl = false;
        // 结算购物车
        if($type==1){
            $shopping_cart_id = input('shopping_cart_id');//购物车id，多个的时候用逗号分隔
            
            // 购物车选中的产品信息列表
            $where[] = ['s.uid','eq',$uid];
            $where[] = ['s.id','in',$shopping_cart_id];
            $list = Db::name('shopping_cart')->alias('s')->join('product p','s.pro_id=p.id','LEFT')->where($where)->field('s.*,p.name,p.sub_name,p.share_img,p.status')->select();
            
            if(!$list){
                $list = array();
            }
            else{
                $is_cgsl = true;
                foreach($list as $value){
                    if($value['status']==-1){
                        errMsg('购物车中存在已下架产品，请重新购买');
                    }
                    if($value['price_sum']>0){
                        $price_sum+=$value['price_sum'];
                    }

                    // 购物车里面是否全是采购送礼的商品，包含的话此次结算不能用优惠券和积分
                    if($value['price_type']!=2){    
                        $is_cgsl = false;
                    }
                }
            }
            $data['product_list'] = $list;
            $data['price_sum'] = sprintf("%.2f",$price_sum);

        }
        else{
            // 结算单个商品
            $pid = input('pid/d');
            $spec = input('spec');
            $num = input('num/d');
            $price_type = input('price_type/d');//选择价格类型，0：普通用户价格，1：内购价格，2：送礼采购价


            if(!$pid||!$spec||!$num){
                errMsg('必传参数缺失');
            }
            $goods_info = Db::name('product')->where('id',$pid)->find();
            if(!$goods_info){
                errMsg('参数错误');
            }

            if($price_type==0){
                $price_arr = explode(',',$goods_info['price']);
                $goods_price = 0;
                if($goods_info['spec']){
                    $spec_arr = explode(',',$goods_info['spec']);
                    foreach($spec_arr as $key=>&$value){
                        if($spec==$value){
                            $goods_price = $price_arr[$key];
                        }
                    }
                }
            }
            elseif($price_type==1){
                $price_arr = explode(',',$goods_info['price_inner']);
                $goods_price = 0;
                if($goods_info['spec']){
                    $spec_arr = explode(',',$goods_info['spec']);
                    foreach($spec_arr as $key=>&$value){
                        if($spec==$value){
                            $goods_price = $price_arr[$key];
                        }
                    }
                }
            }
            elseif($price_type==2){
                $goods_price = $goods_info['slcg_price'];
                $rest_num_del = $goods_info['unit_transform']*$num;
                if($rest_num_del>$goods_info['rest_num']){
                    errMsg('库存不足');
                }

                // 商品是否采购送礼的商品，是的话此次结算不能用优惠券和积分
                $is_cgsl = true;
            }
            
            $return_goods_info[] = array(
                'pro_id'=>$goods_info['id'],
                'spec_select'=>$spec,
                'spec_price'=>$goods_price,
                'num'=>$num,
                'price_sum'=>$goods_price*$num,
                'name'=>$goods_info['name'],
                'sub_name'=>$goods_info['sub_name'],
                'share_img'=>$goods_info['share_img'],
            );
            $data['product_list'] = $return_goods_info;
            $data['price_sum'] = sprintf("%.2f",$goods_price*$num);
            $price_sum = $goods_price*$num;

        }

        // 选择了送礼采购，不能使用积分和优惠券
        if($is_cgsl){
            $data['quan_list'] = array();
            $jifen_status = 0;
            $jifen_money = 0;
            $jifen_desc = '';
            $my_jifen = 0;
        }
        else{
            $time = time();
            // 查询用户可用的优惠券
            $qwhere[] = ['a.uid','eq',$uid];
            $qwhere[] = ['a.status','eq',0];
            $qwhere[] = ['b.use_end_time','gt',$time];
            $qwhere[] = ['b.money_begin','elt',$price_sum];
            
            $quan_list = Db::name('user_quan')->alias('a')->join('product_quan b','a.quan_id=b.id','left')->where($qwhere)->field('a.*,b.quan_name,b.use_end_time,b.money_begin,b.money_del,quan_desc,b.use_bg_time,b.use_end_time')->select();
            
            if(!$quan_list){
                $quan_list = array();
            }
            else{
                foreach($quan_list as $kk=>&$vv){
                    $vv['youxiaoqi'] = date('Y-m-d',$vv['use_bg_time'])."至".date('Y-m-d',$vv['use_end_time']);
                }
            }
            
            $data['quan_list'] = $quan_list;
            
            $jifen_status = 0;
            $jifen_money = 0;
            $jifen_desc = '';
            $my_jifen = 0;
            // 查询用户可用积分
    
            $user_info = Db::name('user')->where('id',$uid)->find();
            // C端用户积分规则
            if($user_info['level']==0){
                $jifen_rule = Db::name('config')->where('id',1)->find();
                // 查看是否开启积分兑换
                if($jifen_rule['jifen_dikou_open']==1){
                    $my_jifen = Db::name('user')->where('id',$uid)->value('jifen');
                    if($my_jifen>0){
                        $dikou_money = floor($my_jifen/$jifen_rule['jifen_dikou']*$jifen_rule['jifen_money_dikou']);
                        if($dikou_money>0){
                            $jifen_desc = "消耗".$my_jifen."积分可抵".$dikou_money."元";
                            $jifen_status = 1;
                            $jifen_money = $dikou_money;
                        }
                    }
                }
            }
            // 内部员工积分规则
            else{
                $jifen_rule = Db::name('config')->where('id',1)->find();
                // 查看是否开启积分兑换
                if($jifen_rule['jifen_dikou_open_inner']==1){
                    $my_jifen = Db::name('user')->where('id',$uid)->value('jifen');
                    if($my_jifen>0){
                        $dikou_money = floor($my_jifen/$jifen_rule['jifen_dikou_inner']*$jifen_rule['jifen_money_dikou_inner']);
                        if($dikou_money>0){
                            $jifen_desc = "消耗".$my_jifen."积分可抵".$dikou_money."元";
                            $jifen_status = 1;
                            $jifen_money = $dikou_money;
                        }
                    }
                }
            }
        }
        
        
        $data['jifen_status'] = $jifen_status;
        $data['jifen'] = $my_jifen;
        $data['jifen_money'] = $jifen_money;
        $data['jifen_desc'] = $jifen_desc;

        okMsg($data);
    }

    

    // 优惠券列表
    function quanList(){
        $pid = input('pid/d');//产品id
        $openid = input('openid/s');

        $uid = $this->getUserId($openid);
        $user_level = Db::name('user')->where('id',$uid)->value('level');
        $time = time();
        // $where[] = ['get_bg_time','gt',$time];
        $where[] = ['get_end_time','lt',$time];
        $where[] = ['rest_num','gt',0];
        $where[] = ['is_delete','eq',0];
        $where[] = ['status','eq',1];
        if($user_level==0){
            $where[] = ['user_type','eq',0];
        }
        elseif($user_level==1){
            $where[] = ['user_type','elt',1];
        }
        elseif($user_level==2){
            $where[] = ['user_type','elt',2];
        }

        $list = Db::name('product_quan')->where($where)->select();
        if($list){
            foreach($list as $key=>&$value){
                if($value['use_bg_time']&&$value['use_end_time']){
                    $value['youxiaoqi'] = date('Y-m-d',$value['use_bg_time'])."至".date('Y-m-d',$value['use_end_time']);
                }
            }
        }
        else{
            $list = array();
        }
        okMsg($list);
    }

    // 领取优惠券
    function getQuan(){
        $openid = input('openid/s');
        $quan_id = input('quan_id/d');
        $uid = $this->getUserId($openid);
        if(!$quan_id||!$uid){
            errMsg('参数错误');
        }
        $quan_info = Db::name('product_quan')->where(array('id'=>$quan_id,'is_delete'=>0,'status'=>1))->find();
        if(!$quan_info){
            errMsg('无此优惠券或优惠券已下架');
        }
        $time = time();
        if($time>$quan_info['get_end_time']){
            errMsg('优惠券领取已结束');
        }
        if($time<$quan_info['get_bg_time']){
            errMsg('优惠券领取未开始');
        }
        if($quan_info['rest_num']<=0){
            errMsg('优惠券已被领完');
        }
        
        $user_level = Db::name('user')->where('id',$uid)->value('level');
        if($user_level==0){
            if($quan_info['user_type']>0){
                errMsg('很抱歉，您不满足此优惠券领取条件');
            }
        }
        elseif($user_level==1){
            if($quan_info['user_type']==2){
                errMsg('很抱歉，您不满足此优惠券领取条件');
            }
        }

        $getQuanNum = Db::name('user_quan')->where(array('quan_id'=>$quan_id,'uid'=>$uid))->count('id');
        if($getQuanNum>=$quan_info['get_limit_num']){
            errMsg('每人限领取'.$quan_info['get_limit_num'].'张');
        }

        $in_data = array(
            'uid'=>$uid,
            'quan_id'=>$quan_id,
            'status'=>0,
            'ctime'=>time()
        );
        $rs = Db::name('user_quan')->insert($in_data);
        if($rs){
            okMsg('领取成功');
        }
        else{
            errMsg('领取失败，请重试');
        }
    }

    // 我的优惠券
    function myQuan(){
        $openid = input('openid/s');
        $serch_type = input('serch_type/d');//搜索类型，0：全部，1：可使用，2：已使用，3：已过期

        $uid = $this->getUserId($openid);


        $time = time();
        // 判断自己是否有券已过期,有的话把已过期的券的状态修改成过期
        // $cwhere[] = ['a.status','eq',0];
        // $cwhere[] = ['b.use_end_time','lt',$time];
        // $cwhere[] = ['b.is_delete','eq',0];
        // $quan_check = Db::name('user_quan')->alias('a')->join('product_quan b','a.quan_id=b.id','left')->where($cwhere)->field('id')->select();
        // if($quan_check){
        //     Db::name('user_quan')->
        // }

        $where[] = ['is_delete','eq',0];
        $where[] = ['uid','eq',$uid];
        if($serch_type==1){
            $where[] = ['a.status','eq',0];
            $where[] = ['b.use_bg_time','lt',$time];
            $where[] = ['b.use_end_time','gt',$time];
        }
        elseif($serch_type==2){
            $where[] = ['a.status','eq',1];
        }
        elseif($serch_type==3){
            $where[] = ['a.status','eq',0];
            $where[] = ['b.use_end_time','lt',$time];
        }
        $list = Db::name('user_quan')->alias('a')->join('product_quan b','a.quan_id=b.id','left')->where($where)->field('a.*,b.use_end_time,b.use_bg_time,b.quan_name,b.quan_desc,b.money_begin,b.money_del,b.type')->select();
        if(!$list){
            $list = array();
        }
        else{
            foreach($list as $key=>&$value){
                if($value['use_bg_time']&&$value['use_end_time']){
                    $value['youxiaoqi'] = date('Y-m-d',$value['use_bg_time'])."至".date('Y-m-d',$value['use_end_time']);
                }
            }
        }

        okMsg($list);
    }

    function getUserId($openid){
        // $wxOauth = new Wxoauth();
        // $id = $wxOauth->getUserId();
        // if(!$id){
        //     noLogin();
        // }
        if(!$openid){
            noLogin();
        }
        $id = Db::name('user')->where('openid',$openid)->value('id');
        return $id;
    }

    // 确认订单
    function setOrders(){
        $type = input('type/d');//下单类型：1：结算购物车（一个或多个产品），2：立即购买某款产品（一个产品）
        $openid = input('openid/s');
        $name = input('name');//收件人姓名
        $phone = input('phone');//收件人电话
        $province = input('province');//收件人省
        $city = input('city');//收件人市
        $district = input('district');//收件人区
        $address = input('address');//收件人地址
        $uid = $this->getUserId($openid);

        // 下单购物车的商品
        if($type==1){
            $shopping_cart_id = input('shopping_cart_id');//要下单的购物车id集
            $quan_id = input('quan_id/d');//要使用的优惠券id
            $is_jifen = input('is_jifen');//是否要使用积分
            $parent_id = input('parent_id/d');//分享人id
            

            if(!$shopping_cart_id){
                errMsg('参数错误');
            }
            $where[] = ['id','in',$shopping_cart_id];
            $list = Db::name('shopping_cart')->where($where)->select();
            if(!$list){
                errMsg('购物车无选中产品');
            }
            $price_sum = 0;
            $is_slcg = 0;
            foreach($list as &$value){
                $pro_id[] = $value['pro_id'];
                $spec[] = $value['spec_select'];
                $num[] = $value['num'];
                $spec_price[] = $value['spec_price'];
                $price_sum += floatval($value['price_sum']);
                if($value['price_type']==2){
                    $is_slcg = 1;//是否包含送礼采购的商品
                }
            }

            if($price_sum>0){
                $quan_money = 0;
                if($quan_id&&$quan_id>0){
                    $quan_info = Db::name('user_quan')->alias('a')->join('product_quan b','a.quan_id=b.id')->where(array('a.id'=>$quan_id,'a.uid'=>$uid))->field('a.*,b.money_begin,b.money_del')->find();
                    if($quan_info&&$quan_info['status']==0&&$quan_info['money_begin']<=$price_sum){
                        // var_dump(1);exit;
                        $quan_money = floatval($quan_info['money_del']);
                    }
                    // var_dump($quan_info['status']);exit;
                }
                $order_price = $price_sum-$quan_money;
                if($order_price>0){
                    // 使用积分
                    $jifen_money = 0;
                    $my_jifen = 0;
                    $jifen_delete = 0;//此次订单扣除的积分
                    if($is_jifen==1){
                        // 查询用户可用积分
                        $jifen_rule = Db::name('config')->where('id',1)->find();
                        // 查看是否开启积分兑换
                        if($jifen_rule['jifen_dikou_open']==1){
                            $my_jifen = Db::name('user')->where('id',$uid)->value('jifen');
                            if($my_jifen>0){
                                $jifen_money = floor($my_jifen/$jifen_rule['jifen_dikou']*$jifen_rule['jifen_money_dikou']);
                                // 订单金额大于积分能抵扣的金额
                                if($order_price>=$jifen_money){
                                    $order_price -= $jifen_money;
                                    $jifen_delete = $jifen_money/$jifen_rule['jifen_money_dikou']*$jifen_rule['jifen_dikou'];
                                    // $jifen_delete = floor($my_jifen/$jifen_rule['jifen_dikou']);
                                }
                                else{
                                    //积分能抵扣的金额大于订单金额，计算应该扣多少积分
                                    $jifen_delete = ceil($order_price/$jifen_rule['jifen_money_dikou']*$jifen_rule['jifen_dikou']);
                                    $jifen_money = $order_price;
                                    $order_price = 0;
                                }
                            }
                        }
                    }
                }
                else{
                    $order_price = 0;
                    $jifen_money = 0;
                    $my_jifen = 0;
                    $jifen_delete = 0;//此次订单扣除的积分
                    $quan_money = 0;
                    $quan_id = 0;
                    $is_jifen = 0;
                }

                
                $in_data = array(
                    'uid'=>$uid,
                    'orders_id'=>date('YmdHis').$uid.mt_rand(1,10000),
                    'goods_id'=>implode(',',$pro_id),
                    'goods_spec'=>implode(',',$spec),
                    'goods_price'=>implode(',',$spec_price),
                    'goods_num'=>implode(',',$num),
                    'all_goods_price'=>$price_sum,
                    'quan_id'=>$quan_id,
                    'order_price'=>$order_price,
                    'quan_id'=>$quan_id,
                    'quan_price'=>$quan_money,
                    'jifen'=>$jifen_delete,
                    'jifen_price'=>$jifen_money,
                    'ctime'=>time(),
                    'last_pay_time'=>time()+86400,
                    'name'=>$name,
                    'phone'=>$phone,
                    'province'=>$province,
                    'city'=>$city,
                    'district'=>$district,
                    'address'=>$address,
                    'parent_id'=>$parent_id,
                    'is_slcg'=>$is_slcg
                );

                $up_data = array('province'=>$province,'city'=>$city,'district'=>$district,'address'=>$address);
                Db::name('user')->where('id',$uid)->update($up_data);
                $rs = Db::name('orders')->insertGetId($in_data);
                if($rs){
                    // 清空选中的购物车
                    $dwhere[] = ['id','in',$shopping_cart_id];
                    $res = Db::name('shopping_cart')->where($dwhere)->delete();
                    // 修改优惠券使用状态
                    if($quan_id&&$quan_id>0){
                        Db::name('user_quan')->where('id',$quan_id)->update(array('status'=>1,'use_time'=>time(),'use_order_id'=>$rs));
                    }
                    // 扣除积分
                    if($jifen_delete>0){
                        Db::name('user')->where('id',$uid)->setDec('jifen',$jifen_delete);
                        // Db::name('user')->where('id',$uid)->update(array('jifen'=>0));
                        // 新增积分抵扣记录
                        $jifen_in_data = array(
                            'uid'=>$uid,
                            'orders_id'=>$in_data['orders_id'],
                            'jifen'=>$jifen_delete,
                            'ctime'=>time(),
                            'month'=>date('m',time()),
                            'year'=>date('Y',time()),
                            'day'=>date('Y-m-d',time()),
                            'type'=>2
                        );
                        Db::name('user_jifen')->insert($jifen_in_data);
                    }
                    $order_price = sprintf("%.2f",$order_price);
                    okMsg(array('order_id'=>$rs,'order_price'=>$order_price));
                }
                else{
                    errMsg('下单失败，请重试');
                }
            }
            else{
                errMsg('订单参数错误，请重试');
            }
            

        }
        // 单个产品下订单
        else{
            $pid = input('pid/d');
            $spec = input('spec/s');//所选规格
            $num = input('num/d');
            $quan_id = input('quan_id/d');//要使用的优惠券id
            $is_jifen = input('is_jifen');//是否要使用积分
            $parent_id = input('parent_id/d');//分享人id
            $price_type = input('price_type/d');//选择价格类型，0：普通用户价格，1：内购价格，2：送礼采购价

            if($price_type==2){
                $is_slcg = 1;//是否包含送礼采购的商品
            }
            else{
                $is_slcg = 0;
            }

            if(!$spec||!$pid||!$num){
                errMsg('参数错误');
            }
            $goods_info = Db::name('product')->where('id',$pid)->find();
            if(!$goods_info){
                errMsg('产品信息有误');
            }

            // 有选规格
            if($spec){
                // 获取数据库产品价格
                $pro_spec_arr = explode(',',$goods_info['spec']);
                if($price_type==0){
                    $pro_price_arr = explode(',',$goods_info['price']);
                    foreach($pro_spec_arr as $k=>&$v){
                        if($spec==$v){
                            $goods_info['pro_price'] = floatval($pro_price_arr[$k]);
                        }
                    }
                }
                elseif($price_type==1){
                    $pro_price_arr = explode(',',$goods_info['price_inner']);
                    foreach($pro_spec_arr as $k=>&$v){
                        if($spec==$v){
                            $goods_info['pro_price'] = floatval($pro_price_arr[$k]);
                        }
                    }
                }
                else{
                    $goods_info['pro_price'] = $goods_info['slcg_price'];
                    // $pro_price_arr = explode(',',$goods_info['price_gift']);
                }
                
                
            }
            // // 没选规格
            // else{
            //     if($price_type==0){
            //         $pro_info['pro_price'] = $pro_info['show_price'];
            //     }
            //     elseif($price_type==1){
            //         $pro_info['pro_price'] = $pro_info['show_price_inner'];
            //     }
            //     else{
            //         $pro_info['pro_price'] = $pro_info['show_price_gift'];
            //     }
            // }

            $price_sum = $goods_info['pro_price']*$num;

            if($price_sum>0){
                $quan_money = 0;
                if($quan_id&&$quan_id>0){
                    $quan_info = Db::name('user_quan')->alias('a')->join('product_quan b','a.quan_id=b.id')->where(array('a.id'=>$quan_id,'a.uid'=>$uid))->field('a.*,b.money_begin,b.money_del')->find();
                    if($quan_info&&$quan_info['status']==0&&$quan_info['money_begin']<=$price_sum){
                        $quan_money = floatval($quan_info['money_del']);
                    }
                }
                $order_price = $price_sum-$quan_money;

                if($order_price>0){
                    // 使用积分
                    $jifen_money = 0;
                    $my_jifen = 0;
                    $jifen_delete = 0;//此次订单扣除的积分
                    if($is_jifen==1){
                        // 查询用户可用积分
                        $jifen_rule = Db::name('config')->where('id',1)->find();
                        // 查看是否开启积分兑换
                        if($jifen_rule['jifen_dikou_open']==1){
                            $my_jifen = Db::name('user')->where('id',$uid)->value('jifen');
                            if($my_jifen>0){
                                $jifen_money = floor($my_jifen/$jifen_rule['jifen_dikou']*$jifen_rule['jifen_money_dikou']);
                                // 订单金额大于积分能抵扣的金额
                                if($order_price>=$jifen_money){
                                    $order_price -= $jifen_money;
                                    $jifen_delete = $jifen_money/$jifen_rule['jifen_money_dikou']*$jifen_rule['jifen_dikou'];
                                    // $jifen_delete = floor($my_jifen/$jifen_rule['jifen_dikou']);
                                }
                                else{
                                    //积分能抵扣的金额大于订单金额，计算应该扣多少积分
                                    $jifen_delete = ceil($order_price/$jifen_rule['jifen_money_dikou']*$jifen_rule['jifen_dikou']);
                                    $jifen_money = $order_price;
                                    $order_price = 0;
                                }
                            }
                        }
                    }
                }
                else{
                    $order_price = 0;
                    $jifen_money = 0;
                    $my_jifen = 0;
                    $jifen_delete = 0;//此次订单扣除的积分
                    $quan_money = 0;
                    $quan_id = 0;
                    $is_jifen = 0;
                }
                // var_dump($quan_money);exit;
                // $order_price = $price_sum-$quan_money-$jifen_money;
                
                $in_data = array(
                    'uid'=>$uid,
                    'orders_id'=>date('YmdHis').$uid.mt_rand(1,10000),
                    'goods_id'=>$pid,
                    'goods_spec'=>$spec,
                    'goods_price'=>$goods_info['pro_price'],
                    'goods_num'=>$num,
                    'all_goods_price'=>$price_sum,
                    'quan_id'=>$quan_id,
                    'order_price'=>$order_price,
                    'quan_price'=>$quan_money,
                    'jifen'=>$jifen_delete,
                    'jifen_price'=>$jifen_money,
                    'ctime'=>time(),
                    'last_pay_time'=>time()+86400,
                    'name'=>$name,
                    'phone'=>$phone,
                    'province'=>$province,
                    'city'=>$city,
                    'district'=>$district,
                    'address'=>$address,
                    'parent_id'=>$parent_id,
                    'is_slcg'=>$is_slcg
                );

                $rs = Db::name('orders')->insertGetId($in_data);
                if($rs){
                    // 修改优惠券使用状态
                    if($quan_id&&$quan_id>0){
                        Db::name('user_quan')->where('id',$quan_id)->update(array('status'=>1,'use_time'=>time(),'use_order_id'=>$rs));
                    }
                    // 扣除积分
                    if($is_jifen&&$jifen_delete>0){
                        Db::name('user')->where('id',$uid)->setDec('jifen',$jifen_delete);

                        $jifen_in_data = array(
                            'uid'=>$uid,
                            'orders_id'=>$in_data['orders_id'],
                            'jifen'=>$jifen_delete,
                            'ctime'=>time(),
                            'month'=>date('m',time()),
                            'year'=>date('Y',time()),
                            'day'=>date('Y-m-d',time()),
                            'type'=>2
                        );
                        Db::name('user_jifen')->insert($jifen_in_data);
                    }
                    $order_price = sprintf("%.2f",$order_price);
                    okMsg(array('order_id'=>$rs,'order_price'=>$order_price));
                }
                else{
                    errMsg('下单失败，请重试');
                }
            }
            else{
                errMsg('订单参数错误，请重试');
            }

        }
    }

    // 微信支付
    function goPay(){
        $order_id = input('order_id/d');
        $openid = input('openid');
        $uid = $this->getUserId($openid);
        // $uid = 1;
        $notify_url = "https://hsq.jiwalgt.com/index.php/index/wxpay/notify1";
        if(!$order_id){
            errMsg('参数错误');
        }
        $orders_info = Db::name('orders')->where(array('id'=>$order_id,'uid'=>$uid,'pay_status'=>0))->find();
        // echo Db::name('orders')->getLastSql();exit;
        // echo Db::name('orders')->getLastSql();exit;
        if(!$orders_info){
            errMsg('参数错误！');
        }
        else{
            if($orders_info['order_price']<=0){
                $rs = Db::name('orders')->where('id',$orders_info['id'])->update(array('pay_status'=>1,'pay_time'=>time()));

                // 减库存
                if($orders_info['is_slcg']==0){
                    $goods_id = $orders_info['goods_id'];
                    $goods_num = $orders_info['goods_num'];
                    $goods_price = $orders_info['goods_price'];
                    $goods_id_arr = explode(',',$goods_id);
                    $goods_num_arr = explode(',',$goods_num);
                    $goods_price_arr = explode(',',$goods_price);
                    $spec_arr = explode(',',$orders_info['goods_spec']);
                    foreach($goods_id_arr as $k=>&$v){
                        $buy_num = intval($goods_num_arr[$k]);

                        $goods_info = Db::name('product')->where('id',$v)->field('spec,rest_num,spec_num')->find();
                        $goods_spec_arr = explode(',',$goods_info['spec']);
                        $spec_num = explode(',',$goods_info['spec_num']);
                        // $goods_rest_num_arr = explode(',',$goods_info['rest_num']);
                        $rest_num_del = 0;
                        foreach($goods_spec_arr as $kk=>&$vv){
                            $rest_num_del += $buy_num*$spec_num[$kk];
                            // if($vv==$spec_arr[$k]){
                            // 	$goods_rest_num_arr[$kk] -= $buy_num;
                            // }
                        }

                        Db::name('product')->where('id',$v)->setDec('rest_num',$rest_num_del);
                        // $p_rest_num_str = implode(',',$goods_rest_num_arr);
                        // Db::name('product')->where('id',$v)->update(array('rest_num'=>$p_rest_num_str));
                        // Db::name('product')->where('id',$v)->setDec('rest_num',$buy_num);
                        Db::name('product')->where('id',$v)->setInc('buy_count',$rest_num_del);
                        $sell_in_data = array(
                            'gid'=>$v,
                            'sell_num'=>$goods_num_arr[$k],
                            'sell_money'=>$goods_price_arr[$k]*$goods_num_arr[$k],
                            'ctime'=>time()
                        );
                        Db::name('product_sell_record')->insert($sell_in_data);
                    }
                }
                else{
                    // 有包含采购送礼
                    $goods_id = $orders_info['goods_id'];
                    $goods_num = $orders_info['goods_num'];
                    $goods_price = $orders_info['goods_price'];
                    $goods_spec = $orders_info['goods_spec'];

                    $goods_id_arr = explode(',',$goods_id);
                    $goods_num_arr = explode(',',$goods_num);
                    $goods_price_arr = explode(',',$goods_price);
                    $goods_spec_arr = explode(',',$goods_spec);

                    foreach($goods_id_arr as $k=>&$v){
                        $goods_info = Db::name('product')->where('id',$v)->field('slcg_spec,slcg_price,spec,rest_num,spec_num,unit_transform')->find();
                        $buy_num = intval($goods_num_arr[$k]);
                        // 采购送礼减库存
                        if($goods_spec_arr[$k]==$goods_info['slcg_spec']){
                            $rest_num_del = $goods_info['unit_transform']*$buy_num;
                            Db::name('product')->where('id',$v)->setDec('rest_num',$rest_num_del);
                            
                            $sell_money = $goods_info['slcg_price']*$buy_num;
                        }
                        else{
                            $goods_spec_arr = explode(',',$goods_info['spec']);
                            $spec_num = explode(',',$goods_info['spec_num']);
                            // $goods_rest_num_arr = explode(',',$goods_info['rest_num']);
                            $rest_num_del = 0;
                            foreach($goods_spec_arr as $kk=>&$vv){
                                $rest_num_del += $buy_num*$spec_num[$kk];
                                // if($vv==$spec_arr[$k]){
                                // 	$goods_rest_num_arr[$kk] -= $buy_num;
                                // }
                            }
                            Db::name('product')->where('id',$v)->setDec('rest_num',$rest_num_del);
                            // Db::name('product')->where('id',$v)->setDec('rest_num',$buy_num);
                            $sell_money = $goods_price_arr[$k]*$buy_num;
                        }
                        Db::name('product')->where('id',$v)->setInc('buy_count',$rest_num_del);

                        $sell_in_data = array(
                            'gid'=>$v,
                            'sell_num'=>$goods_num_arr[$k],
                            'sell_money'=>$sell_money,
                            'ctime'=>time()
                        );
                        Db::name('product_sell_record')->insert($sell_in_data);
                    }
                }

                $result=array('error'=>200,'text'=>'支付成功','is_free'=>1);
                echo json_encode($result);exit;
            }

            $datas = array('out_trade_no'=>$orders_info['orders_id'],'total_fee'=>$orders_info['order_price'],'subject'=>'购买商品','body'=>'购买商品');
            
            $wxdata['appid']=config('APPID');
            $wxdata['mch_id']=config('WX_MCH_ID');
            $wxdata['openid']=$openid;
            $paykey=config('WX_SIGN_KEY');
            
            $wxdata['nonce_str']=$this->getRandomStr();
            $wxdata['sign_type']='MD5';
            $wxdata['body']='支付订单金额';
            $wxdata['out_trade_no']=$orders_info['orders_id'];
            $wxdata['total_fee']=$orders_info['order_price']*100;
            $wxdata['spbill_create_ip']=$this->get_client_ip();
            // if($type==1){
            // $wxdata['notify_url']=str_replace('https','http',ADMIN_URL).'resultShopOrder_pt.php';
            // }else{
            // $wxdata['notify_url']=str_replace('https','http',ADMIN_URL).'resultShopOrder_circle.php';
            // }
            //echo $wxdata['notify_url'];
            $wxdata['notify_url']=$notify_url;
            $wxdata['trade_type']='JSAPI';
            //$wxdata['openid']=$openid;
            //$paykey='aabbccvbnfgdgdfgfg11191111335333';

            // file_put_contents('product.txt',json_encode($wxdata));
            // $wxdata['profit_sharing'] = 'Y';//设置分账时需传入
            
            $wxdata['sign']=$this->getSign($wxdata,$paykey);
            
            ksort($wxdata);
            $postxml=$this->arrayToXml($wxdata);

            ob_start();
            $context=array('http'=>array('method'=>'POST','header' => "Content-type: application/xml;charset:utf-8;",'content'=>$postxml));
            $c=stream_context_create($context);
            $xml=file_get_contents('https://api.mch.weixin.qq.com/pay/unifiedorder',false,$c);
            // var_dump($xml);exit;
            $resultdata=simplexml_load_string($xml);
            if($resultdata->return_code=='SUCCESS'&&$resultdata->result_code=='SUCCESS'){
                $randstr=$this->getRandomStr();
                $nowtime=time();
                $paysignarr=array('appId'=>config('APPID'),'timeStamp'=>$nowtime,'nonceStr'=>$randstr,'package'=>'prepay_id='.$resultdata->prepay_id,'signType'=>'MD5');
                Db::name('orders')->where('id',$order_id)->update(array('prepay_id'=>$resultdata->prepay_id));
                ksort($paysignarr);
                ////$signstr=implode('&',$paysignarr);
                
                //$paysign=md5($signstr.'&key='.$paykey);
                $paysign=$this->getSign($paysignarr,$paykey);
                $paydata=array('timeStamp'=>$nowtime,'nonceStr'=>$randstr,'package'=>'prepay_id='.$resultdata->prepay_id,'signType'=>'MD5','paySign'=>$paysign);
                $result=array('error'=>200,'text'=>'调起支付成功','paydata'=>$paydata,'is_free'=>0);
                
                echo json_encode($result);exit;
            }else{
                // var_dump($xml);exit;
                file_put_contents('wxpayerror.txt',$xml);
                echo json_encode(array('text'=>'发起支付失败,请稍后再试','error'=>0));exit;
                
            }
        }
    }

    // 判断上级用户是否分销商,是的话让前端缓存起来,不是的话就不缓存
    function checkParentLevel(){
        $openid = input('openid/s');
        $pid = input('pid/d');
        if($pid>0){
            $p_level = Db::name('user')->where('id',$pid)->value('level');
            if(!$p_level){
                $p_level = 0;
            }
        }
        else{
            $p_level = 0;
        }
        okMsg(array('parent_level'=>$p_level));
    }

    function getRandomStr(){
		$str=str_shuffle("123jr0ewri23dasdkzxmcadskjafiq1i96763425032185904234320553477eqnnasclikmfanvzcvbqweitretrepoiasdkjgfdnxmzcz");
		return substr($str,0,32);
	}

    function get_client_ip($type = 0) {
        $IP = request()->ip();
        return $IP;
        // $type       =  $type ? 1 : 0;
        // $ip         =   'unknown';
        // if ($ip !== 'unknown') return $ip[$type];
        // if($_SERVER['HTTP_X_REAL_IP']){//nginx 代理模式下，获取客户端真实IP
        //     $ip=$_SERVER['HTTP_X_REAL_IP'];
        // }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
        //     $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        // }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
        //     $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        //     $pos    =   array_search('unknown',$arr);
        //     if(false !== $pos) unset($arr[$pos]);
        //     $ip     =   trim($arr[0]);
        // }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        //     $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
        // }else{
        //     $ip=$_SERVER['REMOTE_ADDR'];
        // }
        // // IP地址合法验证
        // $long = sprintf("%u",ip2long($ip));
        // $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        // return $ip[$type];
    }

    // 签名函数
	public function getSign($Obj,$key)
	{
		foreach ($Obj as $k => $v)
		{
			$Parameters[$k] = $v;
		}
		//签名步骤一：按字典序排序参数
		ksort($Parameters);
		$String = $this->formatBizQueryParaMap($Parameters, false);
		//echo '【string1】'.$String.'</br>';
		//签名步骤二：在string后加入KEY
		$String = $String."&key={$key}";
		//echo "【string2】".$String."</br>";
		//签名步骤三：MD5加密
		$String = md5($String);
		//echo "【string3】 ".$String."</br>";
		//签名步骤四：所有字符转为大写
		$result_ = strtoupper($String);
		//echo "【result】 ".$result_."</br>";
		return $result_;
	}

	function formatBizQueryParaMap($paraMap, $urlencode)
	{
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v)
		{
		    if($urlencode)
		    {
			   $v = urlencode($v);
			}
			//$buff .= strtolower($k) . "=" . $v . "&";
			$buff .= $k . "=" . $v . "&";
		}
		if (strlen($buff) > 0) 
		{
			$reqPar = substr($buff, 0, strlen($buff)-1);
		}
		return $reqPar;
	}

	function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
        	 if (is_numeric($val))
        	 {
        	 	$xml.="<".$key.">".$val."</".$key.">"; 

        	 }
        	 else
        	 	$xml.="<".$key.">".$val."</".$key.">";  
        }
        $xml.="</xml>";
        return $xml; 
    }

    // 积分商城商品列表
    function jifenProduct(){
        $page = input('start/d');
		$num = input('limit/d');
        if(!$page){
            $page = 1;
        }
        if(!$num){
            $num = 20;
        }
        $star = ($page-1)*$num;

        $where[] = ['a.status','eq',1];
        $list = Db::name('product_jifen')->alias('a')->join('product b','a.pid=b.id','left')->where($where)->order('b.orders asc,b.ctime desc')->limit($star,$num)->field('a.*,b.banner,b.share_img,b.name,b.sub_name')->select();
        if($list){
            $data['start'] = $page+1;
            foreach($list as &$value){
                $value['buy_count'] = $value['buy_count']+$value['other_buy_count'];
            }
        }
        else{
            $list = array();
            $data['start'] = -1;
        }

        $data['data'] = $list;
        $data['limit'] = $num;
        $data['msg'] = '获取成功';
        $data['code'] = 200;
        echo json_encode($data);exit;

    }

    // 积分商品详情
    function jifenProductDetail(){
        $openid = input('openid/s');
        // var_dump($openid);exit;
        $uid = $this->getUserId($openid);
        $product_id = input('product_id/d');
        $list = array();
        $where[] = ['a.id','eq',$product_id];
        $where[] = ['a.status','eq',1];
        $product_info = Db::name('product_jifen')->alias('a')->join('product b','a.pid=b.id','left')->where($where)->field('a.*,b.banner,b.share_img,b.name,b.sub_name,b.describes,b.rest_num as p_rest_num,b.spec as new_spec')->find();
        // echo Db::name('product')->getLastSql();exit;
        if(!$product_info){
            errMsg('无此产品');
        }
        if($product_info['describes']){
            $product_info['describes'] = html_entity_decode($product_info['describes']);
        }
        

        $rest_num_arr = explode(',',$product_info['p_rest_num']);
        $new_spec_arr = explode(',',$product_info['new_spec']);
        // $rest_num_sum = 0;
        foreach($rest_num_arr as $k=>$v){
            if($new_spec_arr[$k]==$product_info['spec']){
                $product_info['rest_num'] = $v;
            }
            // $rest_num_sum += $v;
        }
        // $product_info['rest_num_sum'] = $rest_num_sum;
        // $product_info['rest_num'] = $product_info['p_rest_num'];
        // $product_info['spec'] = $product_info['new_spec'];
        // unset($product_info['p_rest_num']);
        $list['product_info'] = $product_info;

        $pinglun_list = Db::name('product_consume')->alias('a')->join("user u",'a.uid=u.id','LEFT')->where(array('a.pid'=>$product_info['pid'],'a.status'=>0))->select();
        $list['pinglun'] = $pinglun_list;
        $list['uid']=$uid;
        $list['type'] = 'jifen';
        // 浏览量+1
        Db::name('product')->where('id',$product_id)->setInc('view_count');
        okMsg($list);
    }

    // 积分商品详情
    function jifenProductDetailQuan(){
        // $openid = input('openid/s');
        // // var_dump($openid);exit;
        // $uid = $this->getUserId($openid);
        $product_id = input('product_id/d');
        $list = array();
        $where[] = ['a.id','eq',$product_id];
        $where[] = ['a.status','eq',1];
        $product_info = Db::name('product_jifen')->alias('a')->join('product b','a.pid=b.id','left')->where($where)->field('a.*,b.banner,b.share_img,b.name,b.sub_name,b.describes,b.rest_num as p_rest_num,b.spec as new_spec')->find();
        // echo Db::name('product')->getLastSql();exit;
        if(!$product_info){
            errMsg('无此产品');
        }
        if($product_info['describes']){
            $product_info['describes'] = html_entity_decode($product_info['describes']);
        }
        

        $rest_num_arr = explode(',',$product_info['p_rest_num']);
        $new_spec_arr = explode(',',$product_info['new_spec']);
        // $rest_num_sum = 0;
        foreach($rest_num_arr as $k=>$v){
            if($new_spec_arr[$k]==$product_info['spec']){
                $product_info['rest_num'] = $v;
            }
            // $rest_num_sum += $v;
        }
        // $product_info['rest_num_sum'] = $rest_num_sum;
        // $product_info['rest_num'] = $product_info['p_rest_num'];
        // $product_info['spec'] = $product_info['new_spec'];
        // unset($product_info['p_rest_num']);
        $list['product_info'] = $product_info;

        $pinglun_list = Db::name('product_consume')->alias('a')->join("user u",'a.uid=u.id','LEFT')->where(array('a.pid'=>$product_info['pid'],'a.status'=>0))->select();
        $list['pinglun'] = $pinglun_list;
        // $list['uid']=$uid;
        $list['type'] = 'jifen';
        // 浏览量+1
        Db::name('product')->where('id',$product_id)->setInc('view_count');
        okMsg($list);
    }

    // 积分商品结算(购物车结算或者是点击立即购买)
    function jifenProductJiesuan(){
        $openid = input('openid/s');
        $uid = $this->getUserId($openid);

        $price_sum = 0;

        // 结算单个商品
        $pid = input('pid/d');
        $num = input('num/d');


        if(!$pid||!$num){
            errMsg('必传参数缺失');
        }

        $my_jifen = Db::name('user')->where('id',$uid)->value('jifen');

        $goods_info = Db::name('product_jifen')->alias('a')->join('product b','a.pid=b.id')->where('a.id',$pid)->field('a.*,b.name,b.sub_name,b.share_img')->find();
        if(!$goods_info){
            errMsg('参数错误');
        }

        $goods_price = $goods_info['price'];
        $goods_jifen = $goods_info['jifen'];
        if($my_jifen<$goods_jifen){
            errMsg('很抱歉，您的积分不足');
        }
        $return_goods_info[] = array(
            'pro_id'=>$goods_info['id'],
            'spec_select'=>$goods_info['spec'],
            'spec_price'=>$goods_price,
            'goods_jifen'=>$goods_jifen,
            'num'=>$num,
            'price_sum'=>$goods_price*$num,
            'name'=>$goods_info['name'],
            'sub_name'=>$goods_info['sub_name'],
            'share_img'=>$goods_info['share_img'],
        );
        $data['product_list'] = $return_goods_info;

        okMsg($data);
    }

    // 确认订单
    function setJifenOrders(){
        $openid = input('openid/s');
        $name = input('name');//收件人姓名
        $phone = input('phone');//收件人电话
        $province = input('province');//收件人省
        $city = input('city');//收件人市
        $district = input('district');//收件人区
        $address = input('address');//收件人地址
        $uid = $this->getUserId($openid);

        // 单个产品下订单
        $pid = input('pid/d');
        $num = input('num/d');


        if(!$pid||!$num){
            errMsg('参数错误');
        }
        $goods_info = Db::name('product_jifen')->where('id',$pid)->find();
        if(!$goods_info){
            errMsg('产品信息有误');
        }
        $order_jifen = $goods_info['jifen']*$num;
        
        $my_jifen = Db::name('user')->where('id',$uid)->value('jifen');

        if($my_jifen<$order_jifen){
            errMsg('很抱歉，您的积分不足');
        }
        // if($goods_info['rest_num']<=0){
        //     errMsg('很抱歉，此商品库存不足');
        // }

        $jifen_spec = $goods_info['spec'];
        $product_info = Db::name('product')->where('id',$goods_info['pid'])->find();
        if($jifen_spec==$product_info['slcg_spec']){
            $rest_num_del = $product_info['unit_transform']*$num;
            if($product_info['rest_num']<$rest_num_del){
                errMsg('很抱歉，此商品库存不足');
            }
        }
        else{
            $spec_arr = explode(',',$product_info['spec']);
            $spec_num = explode(',',$product_info['spec_num']);
            foreach($spec_arr as $kk=>$vv){
                if($vv==$jifen_spec){
                    $rest_num_del = $spec_num[$kk]*$num;
                }
            }
            if($product_info['rest_num']<$rest_num_del){
                errMsg('很抱歉，此商品库存不足');
            }
        }

        $price_sum = $goods_info['price']*$num;

        if($price_sum>0||$goods_info['jifen']){
            
            $order_price = $price_sum;
            if($order_price<0){
                $order_price = 0;
            }
            
            $in_data = array(
                'uid'=>$uid,
                'orders_id'=>date('YmdHis').$uid.mt_rand(1,10000),
                'goods_id'=>$goods_info['pid'],
                'goods_spec'=>$goods_info['spec'],
                'goods_price'=>$goods_info['price'],
                'goods_num'=>$num,
                'goods_jifen'=>$goods_info['jifen'],
                'order_price'=>$order_price,
                'order_jifen'=>$order_jifen,
                'ctime'=>time(),
                'last_pay_time'=>time()+86400,
                'name'=>$name,
                'phone'=>$phone,
                'province'=>$province,
                'city'=>$city,
                'district'=>$district,
                'address'=>$address,
                'type'=>1
            );

            $up_data = array('province'=>$province,'city'=>$city,'district'=>$district,'address'=>$address);
            Db::name('user')->where('id',$uid)->update($up_data);

            $rs = Db::name('orders')->insertGetId($in_data);
            if($rs){
                // 扣除积分
                if($order_jifen){
                    Db::name('user')->where('id',$uid)->setDec('jifen',$order_jifen);
                }
                // 新增积分消耗记录
                $jifen_in_data = array(
                    'uid'=>$uid,
                    'orders_id'=>$in_data['orders_id'],
                    'jifen'=>$order_jifen,
                    'ctime'=>time(),
                    'month'=>date('m',time()),
                    'year'=>date('Y',time()),
                    'day'=>date('Y-m-d',time()),
                    'type'=>2
                );
                Db::name('user_jifen')->insert($jifen_in_data);
                okMsg(array('order_id'=>$rs,'order_price'=>$order_price,'order_jifen'=>$order_jifen));
            }
            else{
                errMsg('下单失败，请重试');
            }
        }
        else{
            errMsg('订单参数错误，请重试');
        }

    }

    // 微信支付
    function goPayJfOrder(){
        $order_id = input('order_id/d');
        $openid = input('openid');
        $uid = $this->getUserId($openid);
        // $uid = 1;
        $notify_url = "https://hsq.jiwalgt.com/index.php/index/wxpay/notify2";
        if(!$order_id){
            errMsg('参数错误');
        }
        $orders_info = Db::name('orders')->where(array('id'=>$order_id,'uid'=>$uid,'pay_status'=>0))->find();
        // echo Db::name('orders')->getLastSql();exit;
        // echo Db::name('orders')->getLastSql();exit;
        if(!$orders_info){
            errMsg('参数错误！');
        }
        else{
            if($orders_info['order_price']>0){
                $datas = array('out_trade_no'=>$orders_info['orders_id'],'total_fee'=>$orders_info['order_price'],'subject'=>'购买积分商城商品','body'=>'购买积分商城商品');
                
                $wxdata['appid']=config('APPID');
                $wxdata['mch_id']=config('WX_MCH_ID');
                $wxdata['openid']=$openid;
                $paykey=config('WX_SIGN_KEY');
                
                $wxdata['nonce_str']=$this->getRandomStr();
                $wxdata['sign_type']='MD5';
                $wxdata['body']='支付订单金额';
                $wxdata['out_trade_no']=$orders_info['orders_id'];
                $wxdata['total_fee']=$orders_info['order_price']*100;
                $wxdata['spbill_create_ip']=$this->get_client_ip();
                // if($type==1){
                // $wxdata['notify_url']=str_replace('https','http',ADMIN_URL).'resultShopOrder_pt.php';
                // }else{
                // $wxdata['notify_url']=str_replace('https','http',ADMIN_URL).'resultShopOrder_circle.php';
                // }
                //echo $wxdata['notify_url'];
                $wxdata['notify_url']=$notify_url;
                $wxdata['trade_type']='JSAPI';
                //$wxdata['openid']=$openid;
                //$paykey='aabbccvbnfgdgdfgfg11191111335333';

                // file_put_contents('product.txt',json_encode($wxdata));
                // $wxdata['profit_sharing'] = 'Y';//设置分账时需传入
                
                $wxdata['sign']=$this->getSign($wxdata,$paykey);
                
                ksort($wxdata);
                $postxml=$this->arrayToXml($wxdata);

                ob_start();
                $context=array('http'=>array('method'=>'POST','header' => "Content-type: application/xml;charset:utf-8;",'content'=>$postxml));
                $c=stream_context_create($context);
                $xml=file_get_contents('https://api.mch.weixin.qq.com/pay/unifiedorder',false,$c);
                // var_dump($xml);exit;
                $resultdata=simplexml_load_string($xml);
                if($resultdata->return_code=='SUCCESS'&&$resultdata->result_code=='SUCCESS'){
                    $randstr=$this->getRandomStr();
                    $nowtime=time();
                    $paysignarr=array('appId'=>config('APPID'),'timeStamp'=>$nowtime,'nonceStr'=>$randstr,'package'=>'prepay_id='.$resultdata->prepay_id,'signType'=>'MD5');
                    Db::name('orders')->where('id',$order_id)->update(array('prepay_id'=>$resultdata->prepay_id));
                    ksort($paysignarr);
                    ////$signstr=implode('&',$paysignarr);
                    
                    //$paysign=md5($signstr.'&key='.$paykey);
                    $paysign=$this->getSign($paysignarr,$paykey);
                    $paydata=array('timeStamp'=>$nowtime,'nonceStr'=>$randstr,'package'=>'prepay_id='.$resultdata->prepay_id,'signType'=>'MD5','paySign'=>$paysign);
                    $result=array('error'=>200,'text'=>'调起支付成功','paydata'=>$paydata);
                    
                    echo json_encode($result);exit;
                }else{
                    var_dump($xml);exit;
                    file_put_contents('wxpayerror.txt',$xml);
                    echo json_encode(array('text'=>'发起支付失败,请稍后再试','error'=>0));exit;
                    
                }
            }
            else{
                $rs = Db::name('orders')->where('orders_id',$orders_info['orders_id'])->update(array('pay_status'=>1,'pay_time'=>time()));
                // 库存处理
                $goods_info = Db::name('product')->where('id',$orders_info['goods_id'])->field('rest_num,spec,spec_unit,unit_transform,slcg_spec')->find();
                if($orders_info['goods_spec']==$goods_info['slcg_spec']){
                    $rest_num_del = $goods_info['unit_transform']*$orders_info['goods_num'];
                }
                else{
                    $spec_arr = explode(',',$goods_info['spec']);
                    $spec_unit = explode(',',$goods_info['spec_unit']);
                    $rest_num_del = 0;
                    foreach($spec_arr as $k=>$v){
                        if($orders_info['goods_spec']==$v){
                            $rest_num_del = intval($spec_unit[$k])*intval($orders_info['goods_num']);
                        }
                    }
                }
                
                Db::name('product')->where('id',$orders_info['goods_id'])->setDec('rest_num',$rest_num_del);
                // Db::name('product')->where('id',$orders_info['goods_id'])->update(array('rest_num'=>$rest_num));

                // 购买量+1
                // $goods_num = intval($orders_info['goods_num']);
                Db::name('product_jifen')->where('pid',$orders_info['goods_id'])->setInc('buy_count',$rest_num_del);

                // 购买量+1
                Db::name('product')->where('id',$orders_info['goods_id'])->setInc('buy_count',$rest_num_del);

                $result=array('error'=>200,'text'=>'支付成功','is_free'=>1);
                echo json_encode($result);exit;
            }
        }
    }

    // 推荐到首页的积分商品列表
    function indexJifenProduct(){
        $where[] = ['a.status','eq',1];
        $where[] = ['a.is_index','eq',1];
        $list = Db::name('product_jifen')->alias('a')->join('product b','a.pid=b.id','left')->where($where)->order('b.orders asc,b.ctime desc')->field('a.*,b.banner,b.share_img,b.name,b.sub_name')->select();
        if(!$list){
           $list = array(); 
        }
        else{
            foreach($list as &$value){
                $value['buy_count'] = $value['buy_count']+$value['other_buy_count'];
            }
        }
        okMsg($list);
    }


}